package com.store.controller;


import com.store.domain.R;
import com.store.utils.Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.io.FileUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author yu
 * @date 2023/5/5
 */
@RestController
@RequestMapping("admin/upload")
public class ImgUploadController {
    // todo 增加一个防止上传过快的拦截
    @PostMapping()
    public R uploadImg(@RequestParam MultipartFile img) {
        Utils utils = new Utils(0, 0);
        String filename = utils.nextId()+".png"; //随机数 + 获取上传文件原来的名称
        String filePath = "/src/main/resources/images";
        File temp = new File(filePath);
        if (!temp.exists()) { //没有这个文件就创建这个文件
            temp.mkdirs();
        }

        try {
            //File.separator 用于在不同的操作系统下，分隔符有的为/,有的为\的问题
            img.transferTo(new File(temp.getAbsolutePath() + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("");
        }
        R r = new R();
        r.setCode(200);
        //拼接完整的路径
        r.setData("http://localhost:9999/admin/upload/" + filename);
        return r;
    }

    @GetMapping("{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File("/src/main/resources/images/" + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
//        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setHeader("Content-Disposition", "inline;filename=" + uploadFile.getName());
        if (fileUUID.endsWith(".jpg")){
            response.setContentType("image/jpg");
        }
        else if (fileUUID.endsWith(".png")){
            response.setContentType("image/png");
        } else {
            response.setContentType("application/octet-stream");
        }

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

}
